<?php

class admin {
	
	private $smarty;
	private $lang;
	public $template;
	public $debug;
	
	function __construct ($lang, $siteDetails, $debug = false)
	{
		$this->lang = $lang;	
		$this->debug = $debug;
		$this->siteDetails = $siteDetails;
	}
	
	public function run(&$smarty)
	{
		if(session_id() == '') {
    		session_start();
		}		
		if (isset($_POST['subAction'])) {
			$action = $_POST['subAction'];
		} elseif (isset($_GET['subAction'])) {
			$action = $_GET['subAction'];
		} else {
			$action = 'mainPanel';
		}
		
		// check if user logon
		if (!isset($_SESSION['user']['id']) && $action != 'trylogin') {
			$action = 'login';
		} 
		
		// print_r($_SESSION); 
		// print $action;


		switch ($action) {
			case 'logout';
				$this->logout();
				break;
			case 'trylogin':
				$template = $this->trylogin($smarty);
				break;
			case 'updateNews':
				$template = $this->updateNews($smarty);
				break;
			case 'mainPanel':	
				$template = $this->mainPanel($smarty);
				break;
			case 'editSong':
				$template = $this->editSong($smarty);
				break;
			case 'updateSong':
				$template = $this->updateSong($smarty);
				break;				
			case 'editNews':
				$template = $this->editNews($smarty);
				break;	
			case 'newSong':
				$template = $this->newSong($smarty);
				break;				
			case 'login':
			default:
				$template = $this->logIn($smarty);
				break;
		}
	
		return $template;
	}
	
	private function logout(){
		$_SESSION = array();
		session_destroy();
		header('location: '.$this->siteDetails->siteUrl);
	}
	
	private function trylogin(&$smarty)
	{
		require_once ("lib/db.php");	
		$dbLogin = new dataBase(false);
		$query = "SELECT * FROM `members` WHERE `nick` = :nick and `password` = :pass";
		$params = array (
							'nick' => array (
											'value' => $_POST['member'],
         									'data_type' =>  'string',
							),
							'pass' => array (
											'value' => $_POST['haslo'],
         									'data_type' =>  'string',
							),
		);
		$dbLogin->paramQuery($query, $params);
		
		print $dbLogin->rowCount();
		
		if ($dbLogin->rowCount() == 1) {
			$row = $dbLogin->dbResultFetch();
			// print_r($row); print '<br/><br/>';
			$_SESSION['user'] = array ( 'id' => $row['id'], 'nick' => $row['nick']);
			
			
			// print_r($_SESSION); print '<br/><br/>';
			$smarty->assign('lastActionInfo', $this->lang['login']['loginOK']);
			return $this->mainPanel($smarty);
		} else {
			$smarty->assign('info', $this->lang['login']['incorect']);
			return $this->logIn($smarty);
		}
	}
	
	private function logIn(&$smarty)
	{
		$smarty->assign('info', $this->lang['login']['welcomeInfo']);
		$smarty->assign('who',  $this->lang['login']['who']);
		$smarty->assign('pass', $this->lang['login']['pass']);
		$smarty->assign('send', $this->lang['login']['send']);

		return 'login.tpl';
	}
	
	private function mainPanel(&$smarty) {
		
		// create list of news to edit
		$newsy = new dataBase(false);
		$query = "SELECT * FROM `news` WHERE 1";
		$newsy->simpleQuery($query);
		$news = $newsy->dbResultFetchAll(); 
		
		//create list of songs
		$songsy = new dataBase(false);
		$query = "SELECT id, label FROM `songs` WHERE 1";
		$songsy->simpleQuery($query);
		$songs = $songsy->dbResultFetchAll(); 
		
		$smarty->assign('songs', $songs);
		$smarty->assign('newsy', $news);
		$smarty->assign('action', 'menu');	
		
		return 'mainPanel.tpl';
	}
	
	private function editSong(&$smarty){
		
		$query = "SELECT * FROM `songs` WHERE id = :songId";
		$params = array (
				'songId' => array (
					'value' => $_GET['param'],
					'data_type' => 'int',
				),
		);	
		$newsy = new dataBase(false);
		$newsy->paramQuery($query, $params);
		$song = $newsy->dbResultFetch(); 
		$song['lyrics'] = htmlspecialchars_decode($song['lyrics']);
		$query = "SELECT id, nick, image, label FROM `members` WHERE 1";
		$authorsDb= new dataBase(false);
		$authorsDb->simpleQuery($query, $params);
		$authors = $authorsDb->dbResultFetchAll(); 
		
		$smarty->assign('authors', $authors);
		$smarty->assign('action', 'updateSong');

		$smarty->assign('song', $song);
		
		return 'band.tpl';
	}
	
	private function newSong(&$smarty){
		
		$song = //$newsy->dbResultFetch(); 
		$song = array (
			'id' => -1,
			'lyrics' => '',
			'label' => '',
			'text' => '',
			'authorMusic' => '',
			'authorLyr' => '',
			'authorMusicZespolId' => 0,
			'authorLyrZespolId' => 0,
			'dateWritten' => '',
			'imageAlt' => '',
		);
		$query = "SELECT id, nick, image, label FROM `members` WHERE 1";
		$authorsDb= new dataBase(false);
		$authorsDb->simpleQuery($query);
		$authors = $authorsDb->dbResultFetchAll(); 
		
		$smarty->assign('authors', $authors);
		$smarty->assign('action', 'updateSong');

		$smarty->assign('song', $song);
		
		return 'band.tpl';
	}
	
	private function updateSong(&$smarty)
	{
		if ($_POST['authorMusic'] < -1	|| $_POST['authorLyrics'] < -1) {
			$smarty->assign('lastActionInfo', 'nie podana autor�w (???)');
			return $this->mainPanel($smarty);
		}
		if ($_POST['authorLyrics'] == -1 ) {
			$authorLyrOther = $_POST['authorLyricsOther'];
		} else {
			$authorLyrOther = '';
		}
		if ($_POST['authorMusic'] == -1 ) {
			$authorMusicOther = $_POST['authorMusicOther'];
		} else {
			$authorMusicOther = '';
		}
		
		$lyrics = htmlspecialchars(stripslashes($_POST['lyrics']));
		
		$params = array (
			'songId' => array (
				'value' => $_POST['songId'],
				'data_type' => 'int',
				),
			'label' => array (
				'value' => $_POST['label'],
				'data_type' => 'str',
				),
			'authorLyrics' => array (
				'value' => $_POST['authorLyrics'],
				'data_type' => 'int',
				),
			'authorLyrOther' => array (
				'value' => $authorLyrOther,
				'data_type' => 'str',
				),
			'authorMusic' => array (
				'value' => $_POST['authorMusic'],
				'data_type' => 'int',
				),
			'authorMusicOther' => array (
				'value' => $authorMusicOther,
				'data_type' => 'str',
				),
			'text' => array (
				'value' => $_POST['text'],
				'data_type' => 'str',
				),
			'dateWritten' => array (
				'value' => $_POST['dateWritten'],
				'data_type' => 'str',
				),
			'songIlustrationTxt' => array (
				'value' => $_POST['songIlustrationTxt'],
				'data_type' => 'str',
				),
			'lyrics' => array (
				'value' => $lyrics,
				'data_type' => 'str',
				),								
);

		if ($_POST['songId'] == -1){ // add new song
			unset($params['songId']);
			$query = "
				INSERT INTO `songs` (`label`, `text`, `authorMusic`, `authorMusicZespolId`, `authorLyr`, `authorLyrZespolId`, `lyrics`, `dateWritten`, `dateAdd2db`, `imageAlt`, `fileName`, `musicId`, `image`	)
				VALUES (
					:label,
					:text,
					:authorMusicOther,
					:authorMusic,
					:authorLyrOther,
					:authorLyrics,
					:lyrics,
					:dateWritten,
					NOW(), 
					:songIlustrationTxt,
					'',
					'',
					''
				)
			";
		} else { // update existing song
		
		
			$query = "
				UPDATE `songs` SET 
					`label`= :label,
					`text`= :text,
					`authorMusic` = :authorMusicOther,
					`authorMusicZespolId` = :authorMusic,
					`authorLyr` = :authorLyrOther,
					`authorLyrZespolId` = :authorLyrics,
					`lyrics` = :lyrics,
					`musicId` = :authorLyrics,
					`dateWritten` = :dateWritten,
					`dateAdd2db` = NOW(), 
					`imageAlt` = :songIlustrationTxt 
				WHERE `id`=:songId
			";
			if(isset($_POST['image']) && $_POST['image'] != '') {
				$params['image'] = array(
					'value' => $_POST['image'],
					'data_type' => 'str',
				);
				$query = "
				UPDATE `songs` SET 
					`label`= :label,
					`text`= :text,
					`authorMusic` = :authorMusicOther,
					`authorMusicZespolId` = :authorMusic,
					`authorLyr` = :authorLyrOther,
					`authorLyrZespolId` = :authorLyrics,
					`lyrics` = :lyrics,
					`musicId` = :authorLyrics,
					`dateWritten` = :dateWritten,
					`dateAdd2db` = NOW(), 
					`imageAlt` = :songIlustrationTxt,
					`image` = :image 
				WHERE `id`=:songId
				";
				}	
		}
			
		$insertSongInDb = new dataBase(false);
		$result = $insertSongInDb->paramQuery($query, $params);
		
		$smarty->assign('lastActionInfo', 'chyba OK');
		return $this->mainPanel($smarty);
	}
	
	private function editNews(&$smarty){
		
		$query = "SELECT * FROM `news` WHERE id = :newsId";
		$params = array (
				'newsId' => array (
				'value' => $_GET['param'],
				'data_type' => 'int',
			),
		);	
		$newsy = new dataBase(false);
		$newsy->paramQuery($query, $params);
		$news = $newsy->dbResultFetch(); 
		$news['text'] = htmlspecialchars_decode($news['text']);
		
		$smarty->assign('action', 'updateNews');
		$smarty->assign('news', $news);
		
		return 'band.tpl';
	}
	
	private function updateNews(&$smarty)
	{
		$text = htmlspecialchars(stripslashes($_POST['text']));	
		$params = array (
			'idUsera' => array (
				'value' => $_SESSION['user']['id'],
				'data_type' => 'int',
				),
			'text' => array (
				'value' => $text,
				'data_type' => 'str',
				),
			'label' => array (
				'value' => $_POST['label'],
				'data_type' => 'str',
				),
			'idNewsa' => array (
				'value' => $_POST['idNewsa'],
				'data_type' => 'int',
				),
			);
		$query = "UPDATE `news` SET `zespol_id` = :idUsera, `text` = :text, `datetime` = NOW(), `label` = :label WHERE `id` = :idNewsa";
		if(isset($_POST['image']) && $_POST['image'] != ''){
			$params['image'] = array(
				'value' => $_POST['image'],
				'data_type' => 'str',
			);
			$query = "UPDATE `news` SET `zespol_id` = :idUsera, `text` = :text, `datetime` = NOW(), `label` = :label, `image` = :image WHERE `id` = :idNewsa";
		}	
			
		$insertNewsInDb = new dataBase(false);
		$insertNewsInDb->paramQuery($query, $params);

		// $news = $newsy->dbResultFetch(); 
		
		$smarty->assign('lastActionInfo', 'chyba OK');
		return $this->mainPanel($smarty);
	}

}
